package cn.song.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Objects;

/**
 * Swagger2配置类
 *
 * @author Song~
 * @since 2024-07-20 14:02:13
 */
@Configuration
@EnableSwagger2
@ConfigurationProperties(prefix = "server.servlet")
public class Swagger2Config {

    @Value("${server.port}")
    private Integer port;

    // @Value("${server.servlet.context_path}") // path前的中横线会导致该文件生成报错
    private String contextPath;


    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("cn.song.module"))
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo() {

        InetAddress address = null;
        try {
            address = InetAddress.getLocalHost();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }

        contextPath = Objects.equals(contextPath, "/") ? "" : "/" + contextPath;

        assert address != null;

        return new ApiInfoBuilder()
                .title("spring-boot-demo项目接口文档")
                .description("spring-boot-demo项目接口文档")
                .contact(new Contact("Song~", "http://" + address.getHostAddress() + ":" + port + contextPath + "/doc.html", "xxxx@xxxx.com"))
                .version("1.0")
                .build();
    }

}
